package com.xiyu.service.repository.material.order;

import com.xiyu.service.model.material.info.MaterialCategoryFetcher;
import com.xiyu.service.model.material.info.MaterialInfoFetcher;
import com.xiyu.service.model.material.order.MaterialInventoryDetailFetcher;
import com.xiyu.service.model.material.order.MaterialInventoryFetcher;
import com.xiyu.service.vo.material.Inventory.InventoryPageQueryInput;
import com.xiyu.service.model.material.order.MaterialInventory;
import com.xiyu.service.model.material.order.MaterialInventoryTable;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;
import java.util.Optional;

public interface MaterialInventoryRepository extends JRepository<MaterialInventory, Long> {
    MaterialInventoryTable materialInventoryTable = MaterialInventoryTable.$;

    default Page<MaterialInventory> pageQuery(InventoryPageQueryInput inputVO){
        return sql().createQuery(materialInventoryTable)
                .whereIf(StringUtils.hasText(inputVO.getInventoryNo()),
                        () -> materialInventoryTable.inventoryNo().like(inputVO.getInventoryNo()))
                .whereIf(inputVO.getWarehouseId() != null,
                        materialInventoryTable.warehouseId().eq(inputVO.getWarehouseId()))
                .whereIf(inputVO.getStatus() != null,
                        () -> materialInventoryTable.status().in(inputVO.getStatus()))
                .orderBy(materialInventoryTable.id().desc())
                .select(materialInventoryTable)
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default Optional<MaterialInventory> findDetailById(Long id){
        return sql().createQuery(materialInventoryTable)
                .where(materialInventoryTable.id().eq(id))
                .select(materialInventoryTable.fetch(
                        MaterialInventoryFetcher.$.allTableFields().details(
                                MaterialInventoryDetailFetcher.$.allTableFields().material(
                                        MaterialInfoFetcher.$.allTableFields().category(
                                                MaterialCategoryFetcher.$.allTableFields()
                                        )
                                )
                        )
                )
                ).fetchOptional();
    }

}